package com.example.config;

import com.example.util.IpKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;

/**
 * @author: dong peng
 * @date: 2019/6/24 15:15
 * @description:
 */

@Component
public class AppInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AppInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String reqURL = request.getRequestURL().toString();
        String ip = IpKit.getRemoteIp(request);
        Map<String, String[]> mapParameters = request.getParameterMap();

        StringBuilder sb = new StringBuilder();
        if( mapParameters != null && mapParameters.size() > 0){
            for(String key : mapParameters.keySet()){
                sb.append(" ["+key+":"+mapParameters.get(key)+"] ");
            }
        }

        InputStream is = request.getInputStream();
        String params = null;
        if( is != null  ){
            byte[] reqBodyBytes = StreamUtils.copyToByteArray(is);
            params = new String(reqBodyBytes);
            sb.append(" > " +params);
        }

        logger.info("[统一请求]IP:{}, URL:{}, 请求参数:{}",ip, reqURL, sb.toString());


        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers",
                "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");

        return true;
    }

}
